# This file is part of Sonedyan.
#
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2009-2012 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>

library(igraph)

# get density of undirected graph
density.undirected <- function(g)
{
	(length(E(g))/ (length(V(g)) * (length(V(g)) - 1) / 2))
}

# get density of correlation matrix at the specified 'temperature'
getDensity <- function(cormat, e)
{
	# get identity matrix with the right size
	nrows <- nrow(cormat)
	id <- diag(rep(1, nrows))
	
	cormat1 <- cormat - id
	cormat1[cormat1 < e] <- -1
	cormat1[cormat1 >= e] <- 1
	cormat1[cormat1 == -1] <- 0
	g <- graph.adjacency(cormat1, mode="min")
	density.undirected(g)
}

# load the subset of 1grams
words <- read.table("core-words.txt")

# load matrix of core normalized time series (subset of 1grams)
mat <- read.table("normalized-core-words.csv", header = FALSE)

# set mat row names
rownames(mat) <- words$V1

# get transpose of matrix
mat2 <- t(mat)
# compute correlation matrix
cormat <- cor(mat2, method="spearman")

# set cormat row/col names
rownames(cormat) <- words$V1
colnames(cormat) <- words$V1

# display density @ specified 'temperature'
for (i in seq(0.984329835,0.984329836, by=0.00000000001))
{
	print(paste(i, " ", getDensity(cormat, i)))
}
